<template>
  <div class="ma-content-block lg:flex justify-between">
    <a-spin style="width: 100%;" :loading="spinLoading" tip="导出中">
      <template #tip>
        <div>
          <a-progress :animation="true" :stroke-width="10" track-color="#d3ccd6" width="130" size="large" type="circle"
            status='warning' :percent="percent" />
          <div style="margin-top: 10px;text-align: center;">{{ exportTxt }}</div>
        </div>

      </template>
      <sa-table ref="crudRef" :options="options" :columns="columns" :searchForm="searchForm" @resetSearch="resetSearch">
        <template #tableSearch>
          <a-col :span="6">
            <a-form-item field="id" label="售后ID">
              <a-input v-model="searchForm.id" placeholder="请输入" :allow-clear="true" @keydown.enter="refresh"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="order" label="订单信息">
              <a-input v-model="searchForm.order" placeholder="订单ID|订单号" :allow-clear="true"
                @keydown.enter="refresh"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="user" label="会员账号">
              <a-input v-model="searchForm.user" placeholder="会员账号" :allow-clear="true"
                @keydown.enter="refresh"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="uid" label="会员UID">
              <a-input v-model="searchForm.uid" placeholder="会员UID" :allow-clear="true"
                @keydown.enter="refresh"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="type" label="售后类型">
              <sa-select :fieldNames="{ value: 'value', label: 'title' }" v-model="searchForm.type"
                :data="paramsData.type" placeholder="请选择" @change="refresh"></sa-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="state" label="状态">
              <sa-select :fieldNames="{ value: 'value', label: 'title' }" v-model="searchForm.state"
                :data="paramsData.state" placeholder="请选择" @change="refresh"></sa-select>
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item field="create_time" label="申请时间">
              <a-range-picker v-model="searchForm.create_time" format="YYYY-MM-DD" :allow-clear="true"
                @change="refresh"></a-range-picker>
            </a-form-item>
          </a-col>
        </template>
        <template #id="{ record }">
          <div>售后ID:{{ record.id }}</div>
          <div class="over_text">状态:{{ record.total_state_text }}{{ record.check_msg }}</div>
        </template>
        <template #order="{ record }">
          <div>订单ID:{{ record.order_id }}</div>
          <div>售后地区:{{ record.area_text }}</div>
        </template>
        <template #user="{ record }">
          <div>UID:{{ record.user_id }}</div>
          <div>会员名:{{ record.user_name }}</div>
        </template>
        <template #time="{ record }">
          <div>售后类型:{{ record.type_text }}</div>
          <div>时间:{{ record.create_time }}</div>
          <div v-if="record.refund_time">退款:{{ record.refund_time }}</div>
        </template>
        <template #sku="{ record }">
          <div v-if="record.sku_list && record.sku_list.length > 0">
            <div v-for="(itm, idx) in record.sku_list" :key="idx">
              <div>{{ itm.sku_name }}({{ itm.num }})</div>
            </div>
          </div>
        </template>
        <template #goods="{ record }">
          <div v-if="record.sku_list && record.sku_list.length > 0">
            <div v-for="(itm, idx) in record.sku_list" :key="idx">
              <div>{{ itm.goods_name }}({{ itm.num }})</div>
            </div>
          </div>

        </template>
        <template #express="{ record }">
          <div>快递:{{ record.express_name }}</div>
          <div>单号:{{ record.express_code }}</div>
        </template>
        <template #attach="{ record }">
          <div v-if="record.img_arr?.length > 0">
            <a-button size="mini" type="outline">查看</a-button>
          </div>
          <div v-else>无</div>
        </template>
        <template #operationAfterExtend="{ record }">
          <div class="custom_btn">
            <a-button type="primary" size="mini" shape="round" @click="detail(record)">详情</a-button>
            <div v-if="record.type == 5 && record.state == 1 && record.intercept_state == 0">
              <a-popconfirm content="确定快递拦截成功吗？" position="bottom" @ok="hanlde('lanjie_success', record)">
                <a-button class="green_color" type="primary" size="mini" shape="round">拦截成功</a-button>
              </a-popconfirm>
              <a-popconfirm content="确定快递拦截失败吗？" position="bottom" @ok="hanlde('lanjie_fail', record)">
                <a-button class="red_color" type="primary" size="mini" shape="round">拦截失败</a-button>
              </a-popconfirm>

            </div>
            <div v-if="(record.type == 1 || record.type == 2 || record.type == 4) && record.state == 1">
              <a-popconfirm content="确定同意吗？" position="bottom" @ok="hanlde('agree', record)">
                <a-button class="green_color" type="primary" size="mini" shape="round">同意</a-button>
              </a-popconfirm>
              <a-popconfirm content="确定拒绝吗？" position="bottom" @ok="hanlde('refuse', record)">
                <a-button class="red_color" type="primary" size="mini" shape="round">拒绝</a-button>
              </a-popconfirm>


            </div>
          </div> 

        </template>
        <template #tableBeforeButtons>
            <a-button type="primary" size="medium" :loading="exportLoading" status="warning"
                style="padding:0 20px;" @click="handleExport"><icon-share-external />导出</a-button>
        </template>
      </sa-table>
    </a-spin>
    <!-- 编辑表单 -->
    <edit-form ref="editRef" @success="refresh" />
    <sa-modal v-model:visible="Modal.visible" :loading="Modal.loading" title="输入拒绝售后原因" @cancel="cancel"
      @ok="hanlde('refuse_modal')">
      <template #self>
        <a-input v-model="Modal.fail_msg" placeholder="请输入拒绝售后原因"></a-input>
      </template>
    </sa-modal>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, computed, watch } from 'vue'
import AsApi from '@/api/system/afterSale'
import SaSelect from '@cps/sa-select/index.vue'
import SaModal from '@cps/sa-modal/index.vue'
import SaTable from '@cps/sa-table/index.vue'
import { Message } from '@arco-design/web-vue'
import { throttle } from 'lodash';
import tool from '@/utils/tool'
import EditForm from './detail.vue'
const exportLoading = ref(false)
const spinLoading = ref(false)
const crudRef = ref()
const editRef = ref()
const signRef = ref()
const Modal = ref({
  visible: false,
  loading: false,
  fail_msg: '',
  id: '',
  state: '',

})
const searchForm = ref({
  order: '',
  user: '',
  state: 99,
  type: 99,
  create_time: [],
  uid: "",
  id: '',
})
const options = reactive({
  api: AsApi.back_exchange_list,//表格数据接口
  operationColumnWidth: 220,//操作欄
  showSearch: true,
  columnAlign: 'left',
  pageSimple: false,//是否展示操作欄有 以及工具欄
  isTreeTable: false,
  showLine: false,
  isExpand: false,//展開所有子樹
})

const columns = reactive([
  { title: 'ID|状态', dataIndex: 'id', width: 200 },
  { title: '订单号', dataIndex: 'order', width: 180 },
  { title: '订单会员', dataIndex: 'user', width: 180 },
  { title: '类型｜时间', dataIndex: 'time', width: 200 },
  { title: 'SKU', dataIndex: 'sku', width: 230 },
  { title: '商品', dataIndex: 'goods', width: 230 },
  { title: '问题描述', dataIndex: 'describe', width: 180 },
  { title: '快递', dataIndex: 'express', width: 180 },
  { title: '附件', dataIndex: 'attach', width: 120 },
])

const initPage = async () => {

}
// const exportExcel = throttle(async () => {
//   exportLoading.value = true
//   const queryParams = new URLSearchParams(searchForm.value).toString();
//   const downloadUrl = `${import.meta.env.VITE_APP_BASE_URL}/shop/admin/after_service/export?fro_source=1${queryParams}`
//   window.location.href = downloadUrl
//   setTimeout(() => {
//     exportLoading.value = false
//   }, 1500);
// }, 3000)
const percent=ref(0)
const intervalId = ref(null)
const handleExport = async () => {
  percent.value = 0
  let params = { ...searchForm.value }
  const { data, code } = await AsApi.export_create_task(params)
  if (code == 200) {
    spinLoading.value = true
    const id = data.id;
    // 定义定时器
    intervalId.value = setInterval(async () => {
      try {
        const res = await AsApi.export_create_progress({ id });
        percent.value = Number(res.data?.percent) / 100
        console.log('进度', percent.value);
        // 判断进度是否达到预期状态，满足条件则停止定时器
        if (res.code === 200 && res.data.state == 1) {
          const url = `${import.meta.env.VITE_APP_BASE_URL}${res.data.excel_path}`
          window.location.href = url;
          spinLoading.value = false
          clearInterval(intervalId.value); // 清除定时器
        } else if (res.code === 0) {
          spinLoading.value = false
          clearInterval(intervalId.value);
        }
      } catch {
        spinLoading.value = false
        clearInterval(intervalId.value);
      }
    }, 2000); // 每2秒执行一次请求
  }
}
const detail = async (record) => {
  editRef.value?.open(record)
  // editRef.value?.getData(record)
}
const sign = (DATA) => {
  signRef.value?.open(DATA)
}
const hanlde = async (type, record = {}) => {
  if (type == 'lanjie_success') {
    try {
      const { data } = await AsApi.bac_express_refuse({ id: record.id, intercept_state: 1 })
      Message.success('操作成功')
      refresh()
    } catch {

    }
  } else if (type == 'lanjie_fail') {
    try {
      const { data } = await AsApi.bac_express_refuse({ id: record.id, intercept_state: 2 })
      Message.success('操作成功')
      refresh()
    } catch {

    }
  } else if (type == 'agree') {
    try {
      const { data } = await AsApi.bac_express_change_states({ id: record.id, state: 2 })
      Message.success('操作成功')
      refresh()
    } catch {

    }
  } else if (type == 'refuse') {
    Modal.value.fail_msg = ''
    Modal.value.id = record.id
    Modal.value.state = 3
    Modal.value.visible = true
  } else {
    try {
      Modal.value.loading = true
      let form = { ...Modal.value }
      const { data } = await AsApi.bac_express_change_states(form)
      Message.success('操作成功')
      Modal.value.visible = false
      refresh()
    } finally {
      Modal.value.loading = false
    }
  }

}
const cancel = () => {
  Modal.value.visible = false
}
const paramsData = ref({})
const getParams = async () => {
  const { data } = await AsApi.back_exchange_list_params()
  paramsData.value = { ...data }
  paramsData.value.state = tool.simpleTransformArray(data.state)
  paramsData.value.state.unshift({ value: 99, title: '全部' })
  paramsData.value.type = tool.simpleTransformArray(data.type)
  paramsData.value.type.unshift({ value: 99, title: '全部' })
}
const refresh = async () => {
  crudRef.value?.refresh()
}
const resetSearch = () => {
  searchForm.value.create_time = []
}
onMounted(async () => {
  initPage()
  refresh()
  getParams()
})
</script>

<style scoped>
.custom_btn {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
}

.icon {
  width: 1em;
}
</style>